﻿@{
    ViewBag.Title = "Set";
    Layout = "~/Views/Shared/_PortraitEditLayout.cshtml";
}

<script language="javascript">
    var pathMarkerIds = {};

    function FeatureActivation() {
        this.style;
        this.element;
    };
        
    function FeatureData() {
        this.active = new Array();
        this.hilight = new FeatureActivation();

        this.containsActive = function (element) {
            for (var i = 0; i < this.active.length; i++) {
                if (this.active[i].element == element) return true;
            }
            return false;
        };

        this.forEachActive = function (fn) {
            for (var i = 0; i < this.active.length; i++) {
                fn(this.active[i]);
            }
        };

        this.addActive = function (element, style) {
            var featureActivation = new FeatureActivation();
            featureActivation.element = element;
            featureActivation.style = style;
            this.active[this.active.length] = featureActivation;
        };

        this.clearActive = function () {
            this.active = new Array();
        }
    };

    var originalFeatureData = new FeatureData();

    var markerPoints = new Array();

    onUpdateFeatures = function (featureTypeId) {
        updateMarkersForFeature(featureTypeId);
        clearFeatures();
    }
    showMarkers = true;

    function addCircle(svg, markerName) {
        var shape = document.createElementNS("http://www.w3.org/2000/svg", "circle");
        shape.setAttribute("r", 10);
        shape.setAttribute("style", "stroke:black;stroke-width:2;fill:red;");
        shape.setAttribute("markername", markerName);
        shape.setAttribute("onmouseover", "updateMarkerName('" + markerName + "')");
        $(svg).find("g").append(shape);
        setDragMethodsToCircleSet($(shape));

        return shape;
    }

    function processDrag(event, ui) {
        //figure out if the current event.target is inside the FullSizeImage svg
        //If it's not, try to find a corresponding circle inside FullSizeImage svg.
        //If it's there, use it, if it's not create it, then use it
        var svg = $('.FullSizeImage svg').get(0);
        var localSvg = $(event.target).parentsUntil("svg").parent().get(0);
        var isLocal = localSvg == svg;

        var markerName = $(event.target).attr("markername")
        var circleToModify = event.target;

        if (!isLocal) {
            var newCircle = $(svg).find("circle[markername='" + markerName + "']").get(0);
            if (newCircle != null) {
                circleToModify = newCircle;
                isLocal = true;
            }
        }

        if (!isLocal) {
            var localMarkerName = $(event.target).attr("markername")

            var shape = addCircle(svg, localMarkerName);
            circleToModify = shape;
        }


        var parentOffset = $('.FullSizeImage svg').first().offset();
        var left = parentOffset.left;
        var top = parentOffset.top;
        var mxy = svg.createSVGPoint();
        mxy.x = ui.offset.left;
        mxy.y = ui.offset.top;
        var newPoint = mxy.matrixTransform(svg.getScreenCTM().inverse());

        circleToModify.setAttribute('cx', newPoint.x);
        circleToModify.setAttribute('cy', newPoint.y);
    }

    function resetCircleHilights() {
        $('circle').each(function (index, element) {
            hilightCircle(element);
        });
    }

    function hilightCircle(target, setHilight) {
        $(target).attr("style", setHilight ? "fill:#00ff00;fill-opacity:1;" : "fill:#ff0000;fill-opacity:1;");
    }

    function setDragMethodsToCircleSet(elements) {
        elements
            .draggable()
            .bind('mousedown', function (event, ui) {
                $(event.target).attr("style", "fill:#00ff00;fill-opacity:1;");
                $(event.target.parentElement).append(event.target);
            })
            .bind('drag', function (event, ui) {
                processDrag(event, ui);
            });
    }

    postProcessSvg = function () {
        setDragMethodsToCircleSet($('circle'));
    };

    function updateMarkerName(markerName) {
        $('#MarkerLabel').html(markerName);
    }

    function clearFeatures() {
        for (var i = 1; i <= 4; i++)
            featureData[i].Id = 0;
    }

    function updateMarkersForFeature(featureTypeId) {
        var svg = $('#MarkerSpace');
        svg.find("g").empty();
        var offset = 12;
        for (var i in markerNames) {
            var shape = addCircle(svg.get(0), markerNames[i]);
            shape.setAttribute("cx", offset);
            offset += 24;
            shape.setAttribute("cy", 12);
        }
    }

    function getFeatureId() {
        for (var i = 1; i <= 4; i++) {
            if (featureData[i].Id > 0)
                return featureData[i].Id;
        }
        return 0;
    }

    function submitSave() {
        $('.FullSizeImage svg')
            .find('circle')
            .each(function (index, element) {
                var point = new Object();
                point.X = $(element).attr("cx").baseVal.value;
                point.Y = $(element).attr("cy").baseVal.value;
                point.MarkerName = $(element).attr("markername");
                markerPoints[index] = point;
            });
        var postData = new Object();
        postData.FeatureId = getFeatureId();
        postData.Markers = markerPoints;

        $.ajax({
            url: 'Save',
            type: 'Post',
            dataType: 'json',
            data: JSON.stringify(postData),
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                apprise('something worked');
            },
            error: function (data) {
                apprise('something failed');
            }
        });
    }

    onSetPortrait = function () {
        $('.FullSizeImage svg').find("path").each(function (index, element) {
            $(element).mouseout(function () {
                if (originalFeatureData.containsActive(element)) return;
                if (originalFeatureData.hilight.element != null) {
                    $(originalFeatureData.hilight.element).attr("style", originalFeatureData.hilight.style);
                }
            });
            $(element).mouseover(function () {
                if (originalFeatureData.containsActive(element)) return;
                if (originalFeatureData.hilight.element != null) {
                    $(originalFeatureData.hilight.element).attr("style", originalFeatureData.hilight.style);
                }

                originalFeatureData.hilight.element = element;
                originalFeatureData.hilight.style = $(element).attr("style");
                $(element).attr("style", "fill:#00ff00;fill-opacity:1;");
            });
            $(element).click(function (e) {
                if (originalFeatureData.containsActive(element)) return;

                resetCircleHilights();

                if (!e.shiftKey) {
                    originalFeatureData.forEachActive(function (activation) {
                        $(activation.element).attr("style", activation.style);
                    });

                    originalFeatureData.clearActive();
                }

                originalFeatureData.addActive(element, originalFeatureData.hilight.style);
                originalFeatureData.hilight.element = null;
                $(element).attr("style", "fill:#5c87b2;fill-opacity:1;");
            });
        });
    }
</script>

<div id="Debug"></div>
<div id="MarkerLabel"></div>
<div id="AvailableMarkers">
    <svg height="24" width="100%" id="MarkerSpace"><g></g></svg>
</div>